package com.xiaopang.product.service.impl;

import com.xiaopang.product.common.DecreaseStockInput;
import com.xiaopang.product.common.ProductInfoOutput;
import com.xiaopang.product.dataobject.ProductInfo;
import com.xiaopang.product.enums.ProductStatusEnum;
import com.xiaopang.product.enums.ResultEnum;
import com.xiaopang.product.exception.ProductException;
import com.xiaopang.product.repository.ProductInfoRepository;
import com.xiaopang.product.service.ProductInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Override
    public List<ProductInfo> findUp() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfoOutput> listForOrder(List<String> productIdList) {
        return productInfoRepository.findByProductIdIn(productIdList).stream()
                .map(e->{
                    ProductInfoOutput productInfoOutput = new ProductInfoOutput();
                    BeanUtils.copyProperties(e,productInfoOutput);
                    return productInfoOutput;
                }).collect(Collectors.toList());
    }

    @Override
    public void decreateStock(List<DecreaseStockInput> cartDTOList) {
        for (DecreaseStockInput decreaseStockInput : cartDTOList) {
            Optional<ProductInfo> productInfoOptional =  productInfoRepository.findById(decreaseStockInput.getProductId());
            //商品不存在
            if(!productInfoOptional.isPresent()){
                log.error("商品{}不存在",decreaseStockInput.getProductId());
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXISTS);
            }
            ProductInfo productInfo = productInfoOptional.get();
            Integer result = productInfo.getProductStock() - decreaseStockInput.getProductQuantity();
            //商品库存不足
            if(result<0){
                log.error("商品{}库存不足",decreaseStockInput.getProductId());
                throw new ProductException(ResultEnum.PRODUCT_STOCT_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }
    }
}
